<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>沐硕博客后台管理系统</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <!-- CSS 优先 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.11.2/dist/css/layui.min.css">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 然后是 JS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/layui@2.11.2/dist/layui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
</head>

<style>
    /* 确保布局结构正确 */
    .layui-layout-admin .layui-side {
        width: 200px;
        left: 0;
        transition: all 0.3s;
    }

    .layui-layout-admin .layui-body {
        left: 200px;
        transition: all 0.3s;
    }

    /* 折叠状态 */
    .layui-layout-admin.layui-layout-small .layui-side {
        left: -200px;
    }

    .layui-layout-admin.layui-layout-small .layui-body {
        left: 0;
    }

    /* 折叠按钮样式 */
    #sidebarToggle {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 20px;
        z-index: 1000;
    }
</style>
<body class="bg-gray-100">
<!-- Layui 管理布局 -->
<div class="layui-layout layui-layout-admin">
    <!-- 头部导航 -->
    <div class="layui-header bg-blue-600 text-white">
        <!-- 系统 Logo -->
        <div class="layui-logo font-bold text-xl">沐硕博客后台</div>
        <!-- 侧边栏切换按钮 -->
        <a href="javascript:;" class="layui-icon layui-icon-spread-left layui-layout-left text-white" id="sidebarToggle"></a>


        <!-- 右侧用户导航 -->
        <ul class="layui-nav layui-layout-right bg-blue-600">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <i class="fa fa-user-circle-o"></i> 管理员
                </a>
            </li>
            <li class="layui-nav-item">
                <a href="/" target="_blank">
                    <i class="fa fa-home"></i> 前台首页
                </a>
            </li>
            <li class="layui-nav-item">
                <a href="/logout">
                    <i class="fa fa-sign-out"></i> 退出登录
                </a>
            </li>
        </ul>
    </div>

    <!-- 侧边栏菜单 -->
    <div class="layui-side layui-bg-black" >
        <div class="layui-side-scroll">
            <ul class="layui-nav layui-nav-tree" lay-filter="sidebar">
                <li class="layui-nav-item layui-nav-itemed">
                    <a href="javascript:;" data-page="dashboard">
                        <i class="fa fa-dashboard"></i> 控制台
                    </a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;" data-page="users">
                        <i class="fa fa-users"></i> 用户管理
                    </a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;" data-page="articles">
                        <i class="fa fa-file-text-o"></i> 文章审核
                    </a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;" data-page="categories">
                        <i class="fa fa-th-list"></i> 分类管理
                    </a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;" data-page="stats">
                        <i class="fa fa-bar-chart"></i> 数据统计
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="layui-body p-4" id="content-container">

        <!-- 加载中提示 -->
        <div class="d-flex justify-center items-center h-full">
            <div class="layui-anim layui-anim-rotate layui-anim-loop">
                <i class="fa fa-circle-o-notch fa-spin text-blue-600 text-4xl"></i>
            </div>
        </div>
    </div>

    <!-- 底部版权信息 -->
    <div class="layui-footer text-center text-gray-500 text-sm" style="height: 35px; line-height: 40px;">
        沐硕博客 © 2025
    </div>
</div>
<!-- 动态页面模板（通过 JS 异步加载） -->

<script>

    <!-- 初始化脚本 -->
    // 初始化 Layui 模块
    layui.use(['element', 'layer', 'jquery', 'table', 'form'], function () {
        var element = layui.element;
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var table = layui.table;
        var form = layui.form;

        // 页面加载初始化
        loadContent('dashboard');

        // 侧边栏点击事件
        $('.layui-nav-tree a[data-page]').on('click', function () {
            var page = $(this).attr('data-page');
            loadContent(page);
            updateSidebarMenu(page);
        });

        // 侧边栏响应式处理

        $('#sidebarToggle').on('click', function () {
            // 切换布局状态
            $('.layui-layout-admin').toggleClass('layui-layout-small');

            // 切换图标
            $(this).toggleClass('layui-icon-spread-left layui-icon-shrink-right');
        });

        // 快速操作按钮点击事件
        $(document).on('click', '.layui-btn[data-page]', function () {
            var page = $(this).attr('data-page');
            loadContent(page);
            updateSidebarMenu(page);
        });


        // 异步加载内容
        function loadContent(page) {
            var container = $('#content-container');
            showLoadingIndicator(container);

            $.ajax({
                url: '/api/admin/content/' + page,
                method: 'GET',
                success: function (response) {
                    container.html(response.content);

                    // 初始化 Layui 组件
                    element.init();
                    form.render();

                    // 特殊页面初始化
                    if (page === 'dashboard') initDashboard();
                    else if (page === 'users') initUserTable();
                    else if (page === 'articles') initArticleTable();
                    else if (page === 'categories') initCategoryTable();
                    else if (page === 'stats') initStatsCharts();
                },
                error: function () {
                    container.html('<div class="alert alert-danger">内容加载失败</div>');
                }
            });
        }

        // 更新导航选中状态
        function updateSidebarMenu(page) {
            $('.layui-nav-tree .layui-nav-item').removeClass('layui-nav-itemed');
            $('.layui-nav-tree a[data-page="' + page + '"]').closest('li').addClass('layui-nav-itemed');
        }

        // 显示加载指示器
        function showLoadingIndicator(container) {
            container.html(`
                <div class="d-flex justify-center items-center h-full">
                    <div class="layui-anim layui-anim-rotate layui-anim-loop">
                        <i class="fa fa-circle-o-notch fa-spin text-blue-600 text-4xl"></i>
                    </div>
                </div>
            `);
        }

        // 初始化导航菜单
        element.init();

        // 控制台页面初始化
        function initDashboard() {
            // 获取统计数据
            fetch('/api/admin/stat/data')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应失败');
                    }
                    return response.json();
                })
                .then(data => {
                    $('#total-users').text(data.users || 0);
                    $('#total-articles').text(data.articles || 0);
                    $('#total-comments').text(data.comments || 0);
                    $('#total-pending').text(data.pending || 0);
                })
                .catch(error => {
                    console.error('获取统计数据失败:', error);
                    $('#total-users, #total-articles, #total-comments, #total-pending')
                        .text('--')
                        .closest('.stat-card')
                        .addClass('bg-red-100 text-red-600');
                    layer.msg('统计数据加载失败，请稍后再试');
                });

            // 初始化趋势图
            const trendChart = echarts.init(document.getElementById('trend-chart'));
            trendChart.setOption({
                title: {text: '数据趋势'},
                tooltip: {},
                legend: {data: ['用户', '文章', '评论']},
                xAxis: {data: ['一月', '二月', '三月', '四月', '五月', '六月']},
                yAxis: {type: 'value'},
                series: [
                    {name: '用户', type: 'line', data: [150, 230, 224, 218, 135, 80]},
                    {name: '文章', type: 'line', data: [80, 130, 180, 210, 250, 300]},
                    {name: '评论', type: 'line', data: [300, 450, 600, 700, 800, 900]}
                ]
            });

            // 最近操作记录
            const recentActions = document.getElementById('recent-actions');
            recentActions.innerHTML = `
                <tr><td>用户登录</td><td>2025-04-05 10:30</td></tr>
                <tr><td>文章发布</td><td>2025-04-05 11:15</td></tr>
                <tr><td>评论审核</td><td>2025-04-05 12:45</td></tr>
            `;
        }

        // 用户管理表格初始化
        function initUserTable() {
            console.log('初始化用户表格...');
            // 使用统一的列定义
            table.render({
                elem: '#userTable',
                url: '/api/admin/user/list',
                cols: userTableCols,
                page: true,
                method: 'GET',
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                response: {
                    statusName: 'code',
                    statusCode: 0,
                    msgName: 'msg',
                    countName: 'count',
                    dataName: 'data'
                },
                parseData: function (res) {
                    console.log('原始响应数据:', res);

                    if (!res) {
                        console.error('无响应数据');
                        return {code: -1, msg: '无响应数据', data: []};
                    }

                    if (Array.isArray(res)) {
                        console.log('检测到数组格式数据');
                        return {code: 0, msg: '', count: res.length, data: res};
                    }

                    if (res.data) {
                        console.log('检测到标准格式数据');
                        return {
                            code: res.code || 0,
                            msg: res.msg || '',
                            count: res.count || (res.data ? res.data.length : 0),
                            data: res.data || []
                        };
                    }

                    console.error('无法识别的数据格式');
                    return {code: -1, msg: '无法识别的数据格式', data: []};
                },
                done: function (res, curr, count) {
                    console.log('表格渲染完成:', res);

                    if (res.code !== 0) {
                        layer.msg('数据加载失败: ' + res.msg);
                    }

                    if (res.data.length === 0) {
                        console.log('无数据');
                        this.elem.next().find('.layui-table-main').html(
                            '<div class="layui-none">暂无数据</div>'
                        );
                    }
                },
                error: function (res, msg) {
                    console.error('表格加载错误:', res, msg);
                    layer.msg('加载失败: ' + msg);
                }
            });
            // 绑定编辑按钮事件
            table.on('tool(userTable)', function (obj) {
                if (obj.event === 'edit') {
                    var data = obj.data;
                    // 打开编辑弹窗
                    layer.open({
                        type: 1,
                        title: '编辑用户',
                        content: $('#editUserForm'),
                        area: ['400px', 'auto'],
                        success: function (layero) {
                            // 填充表单数据
                            $('#editUserId').val(data.userId);
                            $('#editUsername').val(data.username);
                            $('#editEmail').val(data.email);
                            $('#editRole').val(data.role);
                            form.render(); // 渲染表单
                        }
                    });
                }
            });

            // 绑定删除按钮事件
            table.on('tool(userTable)', function (obj) {
                if (obj.event === 'delete') {
                    console.log('删除用户:', obj.data)
                    var data = obj.data;
                    layer.confirm('确定要删除用户 "' + data.username + '" 吗？', {
                        icon: 3,
                        title: '提示'
                    }, function (index) {
                        // 发送DELETE请求到后端删除用户接口
                        $.ajax({
                            type: 'DELETE',
                            url: '/api/admin/user/' + data.userId,
                            headers: {
                                'Authorization': 'Bearer' + localStorage.getItem('token') // 假设令牌存储在 localStorage 中
                            },
                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg('删除成功', {icon: 1}, function () {
                                        layer.close(index); // 关闭确认弹窗
                                        table.reload('userTable'); // 刷新表格
                                    });
                                } else {
                                    layer.msg(res.msg, {icon: 5});
                                }
                            },
                            error: function (err) {
                                layer.msg('删除失败', {icon: 5});
                            }
                        });
                    });
                }
            });

            // 搜索按钮点击事件
            $('#user-search-btn').click(function () {
                var keyword = $('#user-search').val();
                table.reload('userTable', {
                    where: {keyword: keyword}
                });
            });

            // 编辑表单提交事件
            form.on('submit(editUserSubmit)', function (data) {
                var userId = $('#editUserId').val();
                var role = data.field.role === '管理员' ? 1 : 0;
                // 发送PUT请求到后端更新用户接口
                $.ajax({
                    type: 'PUT',
                    url: '/api/admin/user/' + userId,
                    contentType: 'application/json',
                    data: JSON.stringify({
                        userId: userId,
                        username: data.field.username,
                        email: data.field.email,
                        role: role
                    }),
                    success: function (res) {
                        if (res.code === 0) {
                            layer.msg('更新成功', {icon: 1}, function () {
                                layer.closeAll(); // 关闭弹窗
                                table.reload('userTable'); // 刷新表格
                            });
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    },
                    error: function (err) {
                        layer.msg('更新失败', {icon: 5});
                    }
                });
                return false; // 阻止表单默认提交
            });
            console.log('............................');
            $(document).on('click', '.layui-btn[data-batch]', function () {
                const action = $(this).attr('data-batch');
                const ids = [];
                $('.layui-table-body tr input[type="checkbox"]:checked').each(function () {
                    ids.push($(this).closest('tr').data('id'));
                });

                if (ids.length === 0) {
                    layer.msg('请选择至少一项');
                    return;
                }

                $.post('/api/admin/user/batch', {action: action, ids: ids}, function () {
                    table.reload('userTable');
                });
            });
            console.log('用户表格开始');
        }

        // 文章审核表格初始化
        function initArticleTable() {
            table.render({
                elem: '#articleTable',
                url: '/api/admin/article/list',
                cols: articleTableCols,
                page: true,
                method: 'GET',
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },

                response: {
                    statusName: 'code',
                    statusCode: 0,
                    msgName: 'msg',
                    countName: 'total',  // 修改为匹配返回数据中的total字段
                    dataName: 'data'    // 修改为匹配返回数据中的items字段
                },
                parseData: function (res) {
                    console.log('原始响应数据:', res);

                    if (!res) {
                        console.error('无响应数据');
                        return {code: -1, msg: '无响应数据', data: []};
                    }
                    if (res.data !== undefined) {
                        console.log('检测到标准分页格式数据');
                        return {
                            code: 0,
                            msg: '',
                            total: res.total,
                            data: res.data
                        };
                    }
                    // 处理数组格式
                    if (Array.isArray(res)) {
                        console.log('检测到数组格式数据');
                        return {code: 0, msg: '', total: res.length, data: res};
                    }

                    // 处理其他可能的格式
                    if (res.data) {
                        console.log('检测到标准格式数据');
                        return {
                            code: res.code || 0,
                            msg: res.msg || '',
                            total: res.total || (res.data ? res.data.length : 0),
                            data: res.data || []
                        };
                    }

                    console.error('无法识别的数据格式');
                    return {code: -1, msg: '无法识别的数据格式', data: []};
                },
                where: {
                    status: $('#article-status').val(),  // 重新获取下拉框值
                    keyword: $('#article-search').val()  // 重新获取搜索框值
                },
                done: function (res, curr, count) {
                    console.log('表格渲染完成:', res);

                    if (res.code !== 0) {
                        layer.msg('数据加载失败: ' + res.msg);
                    }

                    if (res.data.length === 0) {
                        console.log('无数据');
                        this.elem.next().find('.layui-table-main').html(
                            '<div class="layui-none">暂无数据</div>'
                        );
                    }
                },
                error: function (res, msg) {
                    console.error('表格加载错误:', res, msg);
                    layer.msg('加载失败: ' + msg);
                }
            });
            console.log('文章表格初始化完成');
            // 搜索按钮点击事件
            $('#article-search-btn').on('click', function () {
                table.reload('articleTable', {
                    where: {
                        status: $('#article-status').val(),
                        keyword: $('#article-search').val()
                    },
                    page: {
                        curr: 1 // 重新从第1页开始
                    }
                });
            });

            // 状态筛选变化事件
            $('#article-status').on('change', function () {
                table.reload('articleTable', {
                    where: {
                        status: $(this).val(),
                        keyword: $('#article-search').val()
                    },
                    page: {
                        curr: 1 // 重新从第1页开始
                    }
                });
            });

            // 工具栏事件
            table.on('tool(articleTable)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                console.log('工具栏事件:', data.articleId);
                if (layEvent === 'view') { // 查看文章
                    layer.open({
                        type: 1,
                        title: '文章详情',
                        // 增加自定义样式类
                        skin: 'article-detail-layer',
                        content: `
            <div class="layui-card">
                <div class="layui-card-header" style="border-bottom: 1px solid #f0f0f0;">
                    <h3 style="margin: 10px 0; font-weight: 500;">${data.title}</h3>
                </div>
                <div class="layui-card-body" style="padding: 20px;">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <dl class="layui-dl-horizontal">
                                <dt>作者:</dt>
                                <dd>${data.authorName || '未知'}</dd>

                                <dt>分类:</dt>
                                <dd>${data.categoryName || '未知'}</dd>

                                <dt>状态:</dt>
                                <dd>
                                    ${getStatusText(data.status)}
                                </dd>
                            </dl>
                        </div>
                        <div class="layui-col-md6">
                            <dl class="layui-dl-horizontal">
                                <dt>创建时间:</dt>
                                <dd>${data.createTime.split('T')[0]}</dd>

                                <dt>内容:</dt>
                                <dd style="white-space: pre-wrap; line-height: 1.8; color: #666;">
                                    ${data.content}
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        `,
                        area: ['700px', 'auto'], // 增大宽度
                        success: function (layero, index) {
                            // 动态计算高度，避免内容溢出
                            layero.css('max-height', $(window).height() - 50);
                        }

                    });
                } else if (layEvent === 'approve') {
                    // 审核通过
                    layer.confirm('确定要通过审核吗？', function (index) {
                            $.ajax({
                                type: 'POST',
                                url: 'localhost:8080/api/article/approve/' + data.articleId,
                                success: function (res) {
                                    if (res.code === 0) {
                                        layer.msg('操作成功');
                                        table.reload('articleTable');
                                    } else {
                                        layer.msg(res.msg || '操作失败');
                                    }
                                    layer.close(index);
                                },
                                error: function (xhr, status, error) {
                                    layer.msg('网络错误: ' + error);
                                    console.error('AJAX错误:', status, error);
                                    layer.close(index);
                                }
                            });
                        });
                } else if (layEvent === 'reject') {
                    // 驳回文章 - 同样优化为使用$.ajax
                    layer.confirm('确定要驳回该文章吗？', function (index) {
                        $.ajax({
                            type: 'POST',
                            url: '/article/reject/' + data.articleId,

                            success: function (res) {
                                if (res.code === 0) {
                                    layer.msg('操作成功');
                                    table.reload('articleTable');
                                } else {
                                    layer.msg(res.msg || '操作失败');
                                }
                                layer.close(index);
                            },
                            error: function (xhr, status, error) {
                                layer.msg('网络错误: ' + error);
                                console.error('AJAX错误:', status, error);
                                layer.close(index);
                            }
                        });
                    });
                } else if (layEvent === 'delete') {
                    layer.confirm('确定要删除该文章吗？', function (confirmIndex) {
                        var loadIndex = layer.load(1); // 显示加载动画

                        authenticatedPost('/article/delete/' + data.articleId, {}, function (res) {
                            layer.close(loadIndex); // 关闭加载动画
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                table.reload('articleTable');
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        }, function (err) {
                            layer.close(loadIndex);
                            layer.msg('请求失败，请重试');
                        });

                        layer.close(confirmIndex); // 关闭确认弹窗
                    });
                }


                // 封装状态转换函数（提升可维护性）
                function getStatusText(status) {
                    const statusMap = {
                        1: '<span style="color: #1E9FFF;">已通过</span>',
                        2: '<span style="color: #FFB800;">待审核</span>',
                        3: '<span style="color: #FF5722;">已驳回</span>'
                    };
                    return statusMap[status] || '<span style="color: #999;">未知</span>';
                }

                // 批量操作
                $('#batch-approve').on('click', function () {
                    var checkStatus = table.checkStatus('articleTable');
                    var ids = checkStatus.data.map(function (item) {
                        return item.id;
                    });

                    if (ids.length === 0) {
                        layer.msg('请选择要操作的文章');
                        return;
                    }

                    layer.confirm('确定要通过选中的文章吗？', function (index) {
                        $.post('/article/batch', {action: 'approve', ids: ids}, function (res) {
                            if (res.code === 0) {
                                layer.msg('操作成功');
                                table.reload('articleTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        });
                        layer.close(index);
                    });
                });

                // 批量驳回
                $('#batch-reject').on('click', function () {
                    var checkStatus = table.checkStatus('articleTable');
                    var ids = checkStatus.data.map(function (item) {
                        return item.id;
                    });

                    if (ids.length === 0) {
                        layer.msg('请选择要操作的文章');
                        return;
                    }

                    layer.confirm('确定要驳回选中的文章吗？', function (index) {
                        $.post('/article/batch', {action: 'reject', ids: ids}, function (res) {
                            if (res.code === 0) {
                                layer.msg('操作成功');
                                table.reload('articleTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        });
                        layer.close(index);
                    });
                });

                // 批量删除
                $('#batch-delete').on('click', function () {
                    var checkStatus = table.checkStatus('articleTable');
                    var ids = checkStatus.data.map(function (item) {
                        return item.id;
                    });

                    if (ids.length === 0) {
                        layer.msg('请选择要操作的文章');
                        return;
                    }

                    layer.confirm('确定要删除选中的文章吗？', function (index) {
                        $.post('/article/batch', {action: 'delete', ids: ids}, function (res) {
                            if (res.code === 0) {
                                layer.msg('操作成功');
                                table.reload('articleTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        });
                        layer.close(index);
                    });
                });
                console.log('文章表格初始化完成');


                // 分类管理表格初始化
                function initCategoryTable() {
                    table.render({
                        elem: '#categoryTable',
                        url: '/api/admin/category/list',
                        cols: categoryTableCols,
                        page: true,
                        method: 'GET',
                        request: {
                            pageName: 'page',
                            limitName: 'limit'
                        },
                        response: {
                            statusName: 'code',
                            statusCode: 0,
                            msgName: 'msg',
                            countName: 'count',
                            dataName: 'data'
                        },
                        parseData: function (res) {
                            console.log('原始响应数据:', res);

                            if (!res) {
                                console.error('无响应数据');
                                return {code: -1, msg: '无响应数据', data: []};
                            }

                            if (Array.isArray(res)) {
                                console.log('检测到数组格式数据');
                                return {code: 0, msg: '', count: res.length, data: res};
                            }

                            if (res.data) {
                                console.log('检测到标准格式数据');
                                return {
                                    code: res.code || 0,
                                    msg: res.msg || '',
                                    count: res.count || (res.data ? res.data.length : 0),
                                    data: res.data || []
                                };
                            }

                            console.error('无法识别的数据格式');
                            return {code: -1, msg: '无法识别的数据格式', data: []};
                        },
                        done: function (res, curr, count) {
                            console.log('表格渲染完成:', res);

                            if (res.code !== 0) {
                                layer.msg('数据加载失败: ' + res.msg);
                            }

                            if (res.data.length === 0) {
                                console.log('无数据');
                                this.elem.next().find('.layui-table-main').html(
                                    '<div class="layui-none">暂无数据</div>'
                                );
                            }
                        },
                        error: function (res, msg) {
                            console.error('表格加载错误:', res, msg);
                            layer.msg('加载失败: ' + msg);
                        }
                    });

                    // 查询分类
                    $('#search-category').on('click', function () {
                        var searchName = $('#search-category-name').val();
                        table.reload('categoryTable', {
                            where: {
                                name: searchName // 假设后端接口支持按name查询，根据实际情况调整
                            },
                            page: {
                                curr: 1
                            }
                        });
                    });

                    // 添加分类按钮点击事件
                    $('#add-category').on('click', function () {
                        layer.open({
                            type: 1,
                            title: '添加分类',
                            content: $('#addCategoryDialog').html(),
                            btn: ['提交', '取消'],
                            area: ['400px', 'auto'],
                            success: function (layero) {
                                form.render();
                            },
                            yes: function (index, layero) {
                                var formData = $(layero).find('form').serialize();
                                $.post('/api/admin/category/add', formData, function (res) {
                                    if (res.code === 0) {
                                        layer.msg('添加成功');
                                        table.reload('categoryTable');
                                        layer.close(index);
                                    } else {
                                        layer.msg('添加失败:' + res.msg);
                                    }
                                });
                            },
                            btn2: function (index, layero) {
                                layer.close(index);
                            }
                        });
                    });

                    // 批量操作
                    $(document).on('click', '.layui-btn[data-batch]', function () {
                        const action = $(this).attr('data-batch');
                        const ids = [];
                        $('.layui-table-body tr input[type="checkbox"]:checked').each(function () {
                            ids.push($(this).closest('tr').data('id'));
                        });

                        if (ids.length === 0) {
                            layer.msg('请选择至少一项');
                            return;
                        }

                        $.post('/api/admin/category/batch', {action: action, ids: ids}, function (res) {
                            if (res.code === 0) {
                                layer.msg('操作成功');
                                table.reload('categoryTable');
                            } else {
                                layer.msg('操作失败:' + res.msg);
                            }
                        });
                    });
                    // 工具条事件（编辑和删除）
                    table.on('tool(categoryTable)', function (obj) {
                        var data = obj.data;
                        var layEvent = obj.event;

                        if (layEvent === 'edit') {
                            layer.open({
                                type: 1,
                                title: '编辑分类',
                                content: `
                            <form class="layui-form">
                                <input type="hidden" name="categoryId" value="${data.categoryId}">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">分类名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="name" value="${data.name}" placeholder="请输入分类名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">优先级</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="priority" value="${data.priority}" placeholder="请输入优先级" class="layui-input">
                                    </div>
                                </div>
                            </form>
                        `,
                                btn: ['保存', '取消'],
                                area: ['400px', 'auto'],
                                success: function (layero) {
                                    form.render();
                                },
                                yes: function (index, layero) {
                                    var formData = $(layero).find('form').serialize();
                                    $.post('/api/admin/category/update', formData, function (res) {
                                        if (res.code === 0) {
                                            layer.msg('编辑成功');
                                            table.reload('categoryTable');
                                            layer.close(index);
                                        } else {
                                            layer.msg('编辑失败:' + res.msg);
                                        }
                                    });
                                },
                                btn2: function (index, layero) {
                                    layer.close(index);
                                }
                            });
                        } else if (layEvent === 'delete') {
                            layer.confirm('确定要删除该分类吗？', function (index) {
                                $.post('/api/admin/category/delete/' + data.categoryId, function (res) {
                                    if (res.code === 0) {
                                        layer.msg('删除成功');
                                        table.reload('categoryTable');
                                    } else {
                                        layer.msg('删除失败:' + res.msg);
                                    }
                                });
                                layer.close(index);
                            });
                        }
                    });
                }

                // 统计图表初始化
                function initStatsCharts() {
                    // 用户增长趋势
                    const userGrowthChart = echarts.init(document.getElementById('user-growth-chart'));
                    userGrowthChart.setOption({
                        title: {text: '用户增长趋势'},
                        tooltip: {trigger: 'axis'},
                        legend: {data: ['新增用户']},
                        xAxis: {type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']},
                        yAxis: {type: 'value'},
                        series: [{name: '新增用户', type: 'line', data: [120, 200, 150, 80, 70, 110, 130]}]
                    });

                    // 文章分类分布
                    const categoryDistributionChart = echarts.init(document.getElementById('category-distribution-chart'));
                    categoryDistributionChart.setOption({
                        title: {text: '文章分类分布'},
                        tooltip: {trigger: 'item'},
                        legend: {orient: 'vertical', left: 'right', data: ['技术', '生活', '旅行', '美食', '其他']},
                        series: [{
                            name: '文章数量',
                            type: 'pie',
                            radius: '50%',
                            data: [
                                {value: 335, name: '技术'},
                                {value: 310, name: '生活'},
                                {value: 234, name: '旅行'},
                                {value: 135, name: '美食'},
                                {value: 1548, name: '其他'}
                            ],
                            emphasis: {
                                itemStyle: {shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)'}
                            }
                        }]
                    });

                    // 文章与评论统计
                    const articleCommentChart = echarts.init(document.getElementById('article-comment-chart'));
                    articleCommentChart.setOption({
                        title: {text: '文章与评论统计'},
                        tooltip: {trigger: 'axis'},
                        legend: {data: ['文章', '评论']},
                        xAxis: {type: 'category', data: ['一月', '二月', '三月', '四月', '五月', '六月']},
                        yAxis: {type: 'value'},
                        series: [
                            {name: '文章', type: 'bar', data: [120, 200, 150, 80, 70, 110]},
                            {name: '评论', type: 'bar', data: [200, 300, 250, 180, 100, 150]}
                        ]
                    });
                }
            });


        }
// 分类管理表格初始化
        function initCategoryTable() {
            table.render({
                elem: '#categoryTable',
                url: '/api/admin/category/list',
                cols: categoryTableCols,
                page: true,
                method: 'GET',
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                response: {
                    statusName: 'code',
                    statusCode: 0,
                    msgName: 'msg',
                    countName: 'count',
                    dataName: 'data'
                },
                parseData: function (res) {
                    console.log('原始响应数据:', res);

                    if (!res) {
                        console.error('无响应数据');
                        return {code: -1, msg: '无响应数据', data: []};
                    }

                    if (Array.isArray(res)) {
                        console.log('检测到数组格式数据');
                        return {code: 0, msg: '', count: res.length, data: res};
                    }

                    if (res.data) {
                        console.log('检测到标准格式数据');
                        return {
                            code: res.code || 0,
                            msg: res.msg || '',
                            count: res.count || (res.data ? res.data.length : 0),
                            data: res.data || []
                        };
                    }

                    console.error('无法识别的数据格式');
                    return {code: -1, msg: '无法识别的数据格式', data: []};
                },
                done: function (res, curr, count) {
                    console.log('表格渲染完成:', res);

                    if (res.code !== 0) {
                        layer.msg('数据加载失败: ' + res.msg);
                    }

                    if (res.data.length === 0) {
                        console.log('无数据');
                        this.elem.next().find('.layui-table-main').html(
                            '<div class="layui-none">暂无数据</div>'
                        );
                    }
                },
                error: function (res, msg) {
                    console.error('表格加载错误:', res, msg);
                    layer.msg('加载失败: ' + msg);
                }
            });

            // 查询分类
            $('#search-category').on('click', function () {
                var searchName = $('#search-category-name').val();
                table.reload('categoryTable', {
                    where: {
                        name: searchName // 假设后端接口支持按name查询，根据实际情况调整
                    },
                    page: {
                        curr: 1
                    }
                });
            });

            // 添加分类按钮点击事件
            $('#add-category').on('click', function () {
                layer.open({
                    type: 1,
                    title: '添加分类',
                    content: $('#addCategoryDialog').html(),
                    btn: ['提交', '取消'],
                    area: ['400px', 'auto'],
                    success: function (layero) {
                        form.render();
                    },
                    yes: function (index, layero) {
                        var formData = $(layero).find('form').serialize();
                        $.post('/api/admin/category/add', formData, function (res) {
                            if (res.code === 0) {
                                layer.msg('添加成功');
                                table.reload('categoryTable');
                                layer.close(index);
                            } else {
                                layer.msg('添加失败:' + res.msg);
                            }
                        });
                    },
                    btn2: function (index, layero) {
                        layer.close(index);
                    }
                });
            });

            // 批量操作
            $(document).on('click', '.layui-btn[data-batch]', function () {
                const action = $(this).attr('data-batch');
                const ids = [];
                $('.layui-table-body tr input[type="checkbox"]:checked').each(function () {
                    ids.push($(this).closest('tr').data('id'));
                });

                if (ids.length === 0) {
                    layer.msg('请选择至少一项');
                    return;
                }

                $.post('/api/admin/category/batch', {action: action, ids: ids}, function (res) {
                    if (res.code === 0) {
                        layer.msg('操作成功');
                        table.reload('categoryTable');
                    } else {
                        layer.msg('操作失败:' + res.msg);
                    }
                });
            });
            // 工具条事件（编辑和删除）
            table.on('tool(categoryTable)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;

                if (layEvent === 'edit') {
                    layer.open({
                        type: 1,
                        title: '编辑分类',
                        content: `
                            <form class="layui-form">
                                <input type="hidden" name="categoryId" value="${data.categoryId}">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">分类名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="name" value="${data.name}" placeholder="请输入分类名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">优先级</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="priority" value="${data.priority}" placeholder="请输入优先级" class="layui-input">
                                    </div>
                                </div>
                            </form>
                        `,
                        btn: ['保存', '取消'],
                        area: ['400px', 'auto'],
                        success: function (layero) {
                            form.render();
                        },
                        yes: function (index, layero) {
                            var formData = $(layero).find('form').serialize();
                            $.post('/api/admin/category/update', formData, function (res) {
                                if (res.code === 0) {
                                    layer.msg('编辑成功');
                                    table.reload('categoryTable');
                                    layer.close(index);
                                } else {
                                    layer.msg('编辑失败:' + res.msg);
                                }
                            });
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                        }
                    });
                } else if (layEvent === 'delete') {
                    layer.confirm('确定要删除该分类吗？', function (index) {
                        $.post('/api/admin/category/delete/' + data.categoryId, function (res) {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                table.reload('categoryTable');
                            } else {
                                layer.msg('删除失败:' + res.msg);
                            }
                        });
                        layer.close(index);
                    });
                }
            });
        }

        // 统计图表初始化
        function initStatsCharts() {
            // 用户增长趋势
            const userGrowthChart = echarts.init(document.getElementById('user-growth-chart'));
            userGrowthChart.setOption({
                title: {text: '用户增长趋势'},
                tooltip: {trigger: 'axis'},
                legend: {data: ['新增用户']},
                xAxis: {type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']},
                yAxis: {type: 'value'},
                series: [{name: '新增用户', type: 'line', data: [120, 200, 150, 80, 70, 110, 130]}]
            });

            // 文章分类分布
            const categoryDistributionChart = echarts.init(document.getElementById('category-distribution-chart'));
            categoryDistributionChart.setOption({
                title: {text: '文章分类分布'},
                tooltip: {trigger: 'item'},
                legend: {orient: 'vertical', left: 'right', data: ['技术', '生活', '旅行', '美食', '其他']},
                series: [{
                    name: '文章数量',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        {value: 335, name: '技术'},
                        {value: 310, name: '生活'},
                        {value: 234, name: '旅行'},
                        {value: 135, name: '美食'},
                        {value: 1548, name: '其他'}
                    ],
                    emphasis: {
                        itemStyle: {shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)'}
                    }
                }]
            });

            // 文章与评论统计
            const articleCommentChart = echarts.init(document.getElementById('article-comment-chart'));
            articleCommentChart.setOption({
                title: {text: '文章与评论统计'},
                tooltip: {trigger: 'axis'},
                legend: {data: ['文章', '评论']},
                xAxis: {type: 'category', data: ['一月', '二月', '三月', '四月', '五月', '六月']},
                yAxis: {type: 'value'},
                series: [
                    {name: '文章', type: 'bar', data: [120, 200, 150, 80, 70, 110]},
                    {name: '评论', type: 'bar', data: [200, 300, 250, 180, 100, 150]}
                ]
            });
        }
    });





</script>
<!-- 主要 JavaScript 逻辑 -->

<script type="text/html" id="roleTpl">
    {{#  if(d.role === 1){ }}
    <span class="layui-badge layui-badge-green">管理员</span>
    {{#  } else { }}
    <span class="layui-badge layui-badge-gray">普通用户</span>
    {{#  } }}
</script>

<script type="text/javascript">
    var userTableCols = [
        [
            { type: 'checkbox' }, // 复选框列
        { field: 'userId', title: 'ID', width: 80 ,align: 'center'},
        { field: 'username', title: '用户名', width: 120,align: 'center' },
        { field: 'email', title: '邮箱', width: 180 ,align: 'center'},
        { field: 'role', title: '角色', width: 100, templet: function(d) {
                return d.role === 1 ? '<span class="text-green-500">管理员</span>' : '<span class="text-gray-600">普通用户</span>';
            },align: 'center' },
        { field: 'createTime', title: '创建时间', width: 160, templet: function(d) {
                return d.createTime.split('T')[0]; // 格式化时间为 YYYY-MM-DD
            } ,align: 'center'},
        { toolbar: '#userBar', title: '操作', width: 160 ,align: 'center'}
        ]
    ];
    var articleTableCols = [
        [ { type: 'checkbox' }, // 复选框列
            { field: 'articleId', title: 'ID', width: 40,align: 'center' },
            { field: 'title', title: '标题', width: 160,align: 'center' },
            {
                field: 'authorName',
                title: '作者',
                width: 80,
                align: 'center',
                templet: function(d) {
                    return d.authorName || '未知';
                }
            },
            {
                field: 'categoryId',
                title: '分类',
                width: 80,
                templet: function(d) {
                    return d.categoryName || '未知';
                },
                align: 'center'
            },
            {
                field: 'status',
                title: '状态',
                width: 80,
                templet: function(d) {
                    switch(d.status) {
                        case 1: return '已通过';
                        case 2: return '待审核';
                        case 3: return '已驳回';
                        default: return '未知';
                    }
                },
                align: 'center'
            },
            // {
            //     field: 'createTime',
            //     title: '创建时间',
            //     width: 160,
            //     templet: function(d) {
            //         if (!d.createTime) return '';
            //         // 处理ISO格式时间 (2025-02-01T10:00:00)
            //         return d.createTime.split('T')[0]; // 只显示日期部分
            //     }
            // },
            { toolbar: '#articleBar', title: '操作', width: 300, align: 'center' }
        ]
    ];
    var categoryTableCols =[
        [
            { type: 'checkbox' }, // 复选框列
            { field: 'categoryId', title: 'ID', width: 80,align: 'center' },
            { field: 'name', title: '分类名称', width: 200,align: 'center' },
            { field: 'priority', title: '优先级', width: 100 ,align: 'center'},
            {
                field: 'createTime',
                title: '创建时间',
                width: 160,
                templet: function (d) {
                    if (!d.createTime) return '';
                    return d.createTime.split('T')[0]; // 假设后端返回的是 ISO 格式时间，只显示日期部分
                }
            },
            { toolbar: '#categoryBar', title: '操作', width: 160,align: 'center' }
            ]
    ];
</script>

</body>
</html>